<?php

/**
 * Created by IntelliJ IDEA.
 * User: zhoumengkang
 * Date: 15/9/24
 * Time: 上午1:07
 */

define('MK_MYSQL_WRITE',       'mysqlWrite');
define('MK_MYSQL_READ',        'mysqlRead');

class DbConfig
{

    public static $dsn;
    public static $user;
    public static $pass;

    public static $mysqlConfig = array(

        MK_MYSQL_WRITE     => array(
            'host'      => 'localhost',
            'port'      => '3306',
            'dbname'    => 'register_center',
            'username'  => 'root',
            'password'  => '',
        ),
        MK_MYSQL_READ     => array(
            0 => array(
                'host'      => 'localhost',
                'port'      => '3306',
                'dbname'    => 'register_center',
                'username'  => 'root',
                'password'  => '',
            ),
        ),
    );

    /**
     * 根据输入获取数据库连接信息
     * @param string $connectType   数据库类型
     * @return bool
     * @throws Exception
     */
    public static function getConnectInfo($connectType = MK_MYSQL_WRITE)
    {
        if ( !isset(self::$mysqlConfig[$connectType]) ) {
            throw new Exception("数据库不存在的配置");
        }

        $connectArray = self::$mysqlConfig[$connectType];

        if( $connectType === MK_MYSQL_READ ) {
            $connectArray = self::getRandom($connectType);
            if($connectArray === false) {
                return false;
            }
        }

        self::$dsn  = 'mysql:host=' . $connectArray['host'] . ';port=' . $connectArray['port'] . ";dbname=" . $connectArray['dbname'];
        self::$user = $connectArray['username'];
        self::$pass = $connectArray['password'];
    }

    /**
     * 根据输入随机获取数据库连接信息
     *
     * @param   string  $connectType    数据库类型
     * @return  array   返回随机获取到的数据库连接信息
     */
    public static function getRandom($connectType)
    {
        if ($connectType !== MK_MYSQL_READ) {
            return false;
        }

        $rand = mt_rand(0,count(self::$mysqlConfig[$connectType])-1);

        return self::$mysqlConfig[$connectType][$rand];
    }
}